package com.browsesoft.authentication;

import javax.servlet.http.HttpServletRequest;

import com.browsesoft.EntityManager;
import com.browsesoft.dbtools.DBTools;
import com.browsesoft.user.User;

/**
 * 简单用户名、口令认证
 */
public class SimpleAuthentication extends AuthenticationMode
{
  public SimpleAuthentication()
  {
  }

  /**
   * authenticate 根据请求内容，得到认证用户，如果设备，抛出认证失败异常
   *
   * @param request HttpServletRequest 请求
   * @return User 认证通过的用户
   */
  public User authenticate(HttpServletRequest request) throws AuthenticationException
  {
    try
    {

//      Hashtable ht = new Hashtable();
//      //设置用户名条件
//      String loginUser = request.getParameter("loginUser");
//      loginUser = new String(loginUser.getBytes("ISO8859-1"));
//      ht.put("ename", loginUser);
//      //设置密码条件
//      String pw = request.getParameter("password");
//      ht.put("password", pw);
//      //设置可用条件
//      ht.put("f_using", "是");
//      //找到用户
//      LinkedList users = EntityManager.getInstance().getObjects(
//          "com.browsesoft.user.User", ht, isCase());
//      return (User) users.get(0);
       //设置用户名条件
       String loginUser = request.getParameter("loginUser");
       loginUser = new String(loginUser.getBytes("ISO8859-1"));
       //设置密码条件
       String pw = request.getParameter("password");
       //找到用户
       User result = EntityManager.getInstance().getUser(
           loginUser,pw, isCase());
       if(result == null)
       {
         throw new AuthenticationException();
       }
       return result;

    }
    catch (Exception ex)
    {
      throw new AuthenticationException();
    }
  }

  /**
   * 看是否区分大小写
   * @param match
   * @return
   */
  private boolean isCase()
  {
    try
    {
      //取出设置的是否区分大小写属性
      String sql = "select f_matchcase from t_setpassrule";
      String[][] temp = DBTools.executeQueryWithTableHead(sql);
      return temp[1][0].equals("区分大小写");
    }
    catch (Exception ex)
    {
      return false;
    }
  }
}
